#include "guish.hpp"
#include <libgen.h>

string expandPrompt(string ps1, ShellState *state)
{
	vector<char> tags = tagString(ps1);
	string ret = "";
	
	for(size_t ii=0; ii<ps1.length(); ii++)
	{
		// This basically emulates bash's prompt specification, since that's
		// probably where the value of PS1 was inherited from.
		// See bash.info 6.9 'printing a prompt'
		if(tags[ii]==tagEscaped) {
			switch(ps1[ii]) {
				case 'u': { // The username of the current user
					ret += state->env.get("USER");
					break;
				}
					
				case 'H': // The hostname
					ret += state->env.get("HOSTNAME");
					break;
				
				case 'h': { // The hostname, up to the first '.'
					string hostname = state->env.get("HOSTNAME");
					const char *cstr = hostname.c_str();
					const char *dot = strchr(cstr, '.');
					if(dot)
						ret += hostname.substr(0, dot-cstr);
					else
						ret += hostname;
					break;
				}
				
				case 'w': {
					ret += state->env.get("PWD");
					break;
				}
				case 'W': {
					string pwd = state->env.get("PWD");
					if(pwd== state->env.get("HOME")) {
						ret += "~";
					} else {
						char *pwdCopy = strdup(pwd.c_str());
						char *base = basename(pwdCopy);
						ret += base;
						free(pwdCopy);
					}
					break;
				}
				case '$': {
					ret += "$";
					break;
				}
				case '\\': {
					ret += "\\";
					break;
				}
				
				// TODO: More possibilities here
			}
		} else if(ps1[ii]=='\\') {
			
		} else {
			ret += ps1[ii];
		}
	}
	
	return ret;
	//return state->envExpand(ret);
}

